package com.huige.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @Author 朱志辉
 * @Create 2024/7/14 下午4:25
 * @Version 1.0
 * Description:   配置类
 */
@Configuration
@ComponentScan("com.huige")
@PropertySource("classpath:jdbc.properties")
//@EnableAspectJAutoProxy//开启aop
@EnableTransactionManagement//开启事务注解的支持
public class JavaConfig {

    //druid连接池
    @Bean
    public DataSource dataSource(@Value("${huige.driver}") String databaseName,
                                 @Value("${huige.url}") String url,
                                 @Value("${huige.username}") String username,
                                 @Value("${huige.password}") String password) {
         DruidDataSource dataSource = new DruidDataSource();
         dataSource.setDriverClassName(databaseName);
         dataSource.setUrl(url);
         dataSource.setUsername(username);
         dataSource.setPassword(password);

         return dataSource;
    }

    //jdbcTemplate
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {

        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);

        return jdbcTemplate;
    }


    @Bean
    public TransactionManager transactionManager(DataSource dataSource) {
        //内部要进行事务的操作，基于的是连接池
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        //需要连接池对象
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }



}
